import { mergecart, cartlist } from '@/utils/api/cartapi'
export default {
    namespaced: true,
    state: {
        //给数据前面加name属性
        list: []
    },
    mutations: {
        //添加商品到购物车
        addList(state, obj) {
            state.list.push(obj)
        },
        //修改数量
        changeNum(state, obj) {
            state.list[obj.index].count += obj.number
        },
        delCart(state, index) {
            state.list.splice(index, 1)
        },
        //加
        jia(state, index) {
            state.list[index].count++
        },
        //减
        jian(state, index) {
            state.list[index].count--
        },
        //全选
        quan(state, flag) {
            state.list.forEach(item => {
                item.selected = flag
            })
        },
        //反选
        fan(state, index) {
            state.list[index].selected = !state.list[index].selected
        },
        //全部删除
        alldel(state) {
            state.list = state.list.filter(item => {
                return !item.selected
            })
        },
        //制空本地购物车
        clearList(state) {
            state.list = []
        },
        //将所有数据写入list
        setList(state, arr) {
            state.list = arr
        }
    },
    getters: {
        //购物车的总件数量
        catenum(state) {
            let sum = 0
            state.list.forEach(item => {
                sum += item.count
            })
            return sum
        },
        //选中的商品
        xuannum(state) {
            let sum = 0
            state.list.forEach(item => {
                if (item.selected) {
                    sum += item.count
                }
            })
            return sum
        },
        //选中的商品的价钱
        allprice(state) {
            let sum = 0
            state.list.forEach(item => {
                if (item.selected) {
                    sum += item.count*item.price
                }
            })
            return sum
        },
        //将list中的数据做一个简单处理，为了合并
        mergelist(state) {
            return state.list.map(item => { return { skuId: item.skuId, selected: item.selected, count: item.count } })
        }
    },
    actions: {
        //vuex中合并购物车中的方法
        async asyncmergecart(context) {
            await mergecart(context.getters.mergelist);
            context.commit('clearList')
        },
        //读取线上的购物车列表
        async asynccartlist(context) {
            let res = await cartlist()
            context.commit('setList', res.result)
        }
    },
}